package net.lb.io.json.field;

import java.lang.reflect.Field;
import net.lb.baseutil.collection.ObjectCollect;
import net.lb.baseutil.collection.StringCache;
import net.lb.io.json.JsonArray;
import net.lb.io.json.JsonObject;

@SuppressWarnings("restriction")
public class ByteField extends JsonField
{
    
    public ByteField(Field field)
    {
        super(field);
    }
    
    @Override
    protected Object getSinlgeJsonValue(Object host, ObjectCollect collect)
    {
        return unsafe.getByte(host, offset);
    }
    
    @Override
    public void setOneDimension(Object value, JsonArray jsonArray, ObjectCollect collect)
    {
        for (byte each : (byte[]) value)
        {
            jsonArray.add(each);
        }
        
    }
    
    @Override
    protected void writeToStringByOneDimension(StringCache cache, Object value, ObjectCollect collect)
    {
        cache.append('[', 10);
        for (byte each : (byte[]) value)
        {
            cache.append(each).append(',');
        }
        if (cache.isCommaLast())
        {
            cache.deleteLast();
        }
        cache.append(']');
    }
    
    @Override
    protected void singleWriteToStr(StringCache cache, Object host, ObjectCollect collect)
    {
        cache.append(jsonKey).append(unsafe.getByte(host, offset)).append(',');
    }
    
    @Override
    protected void fillSingle(JsonObject jsonObject, Object target)
    {
        Byte value = jsonObject.getLong(name).byteValue();
        if (value != null)
        {
            unsafe.putByte(target, offset, value.byteValue());
        }
    }
    
    @Override
    protected Object getOneDimensionArray(JsonArray jsonArray)
    {
        byte[] array = new byte[jsonArray.size()];
        for (int i = 0; i < array.length; i++)
        {
            array[i] = jsonArray.getLong(i).byteValue();
        }
        return array;
    }
    
}
